﻿using System.Net.Sockets;

namespace BlazorAdmin.Tcp.Server
{
    /// <summary>
    /// 缓冲区管理
    /// </summary>
    internal class BufferManager
    {
        private readonly int numBytes;
        private readonly int bufferSize;
        private readonly byte[] buffer;
        private int currentIndex;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="totalBytes">总字节缓冲区大小，是<paramref name="bufferSize"/>的倍数</param>
        /// <param name="bufferSize">单个对象所占字节缓冲区大小</param>
        public BufferManager(int bufferSize, int totalBytes)
        {
            buffer = new byte[totalBytes];
            numBytes = totalBytes;
            currentIndex = 0;
            this.bufferSize = bufferSize;
        }

        /// <summary>
        /// 设置Socket异步对象的缓冲区
        /// </summary>
        /// <param name="args">Socket异步对象</param>
        /// <returns></returns>
        public bool SetBuffer(SocketAsyncEventArgs args)
        {
            if (numBytes - bufferSize < currentIndex)
                return false;

            args.SetBuffer(buffer, currentIndex, bufferSize);
            currentIndex += bufferSize;
            return true;
        }
    }
}
